﻿using B.S.XZYData.Api.Read.Application.Command.Account;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System.Data;

namespace B.S.XZYData.Api.Read.Application.Handler.Account
{
    public class GetAccountPageHandler : IRequestHandler<GetAccountPageCommand, ApiPageing<AccountDTO>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IBaseRepository<AccountRoleModel> accountroleRepo;

        public GetAccountPageHandler(IBaseRepository<AccountModel> accountRepo,IBaseRepository<RoleModel> roleRepo,IBaseRepository<AccountRoleModel> accountroleRepo)
        {
            this.accountRepo = accountRepo;
            this.roleRepo = roleRepo;
            this.accountroleRepo = accountroleRepo;
        }

        public async Task<ApiPageing<AccountDTO>> Handle(GetAccountPageCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiPageing<AccountDTO>();
            try
            {
                // 获取所有账户
                var accounts = accountRepo.GetAll().Where(x => !x.IsDeleted).ToList();
                
                // 过滤账户名称
                if (!string.IsNullOrEmpty(request.Name))
                {
                    accounts = accounts.Where(x => x.Name.Contains(request.Name)).ToList();
                }

                // 获取所有账户角色关系
                var accountRoles = accountroleRepo.GetAll().Where(x => !x.IsDeleted).ToList();
                
                // 获取所有角色
                var roles = roleRepo.GetAll().Where(x => !x.IsDeleted).ToList();

                // 构建结果
                var result = new List<AccountDTO>();
                foreach (var account in accounts)
                {
                    var accountRoleIds = accountRoles.Where(ar => ar.AccountId == account.Id).Select(ar => ar.RoleId).ToList();
                    var accountRoleNames = roles.Where(r => accountRoleIds.Contains(r.Id)).Select(r => r.RoleName).ToList();
                    
                    result.Add(new AccountDTO
                    {
                        Id = account.Id,
                        Name = account.Name,
                        Pwd = account.Pwd,
                        RealName = account.RealName,
                        IsState = account.IsState,
                        CreateTime = account.CreateTime,
                        RoleIds = accountRoleIds,
                        RoleName = accountRoleNames
                    });
                }

                // 排序和分页
                var orderedResult = result.OrderByDescending(x => x.CreateTime).ToList();
                var totalCount = orderedResult.Count;
                var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.Size);
                var pageData = orderedResult.Skip((request.Index - 1) * request.Size).Take(request.Size).ToList();

                res.TotaCount = totalCount;
                res.TotaPage = totalPage;
                res.PageData = pageData;
                res.Msg = "查询用户列表成功!";
                res.Code = ApiEnum.Success;
                return await Task.FromResult(res);
            }
            catch (Exception ex)
            {
                res.Msg = "查询用户列表异常!"+ex.Message;
                res.Code = ApiEnum.Error;
                return await Task.FromResult(res);
            }
        }
    }
}
